package net.crozz.openapi.http;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class Param {
    public final Boolean isHeader;
    public final String  name;
    public final String  value;
    public final String  filename;
    public final byte[]  content;

    public Param(Boolean isHeader, String name, String value, String filename, byte[] content) {
        if (name == null || "".equals(name)) {
            throw new IllegalArgumentException("name can not be blank!");
        }

        this.isHeader = isHeader;
        this.name = name;
        this.value = value;
        this.filename = filename;
        this.content = content;
    }

    public static Param newParam(String name, Object value) {
        if (value == null) {
            return new Param(true, name, null, null, null);
        }
        return new Param(false, name, String.valueOf(value), null, null);
    }

    public static Param headerParam(String name, String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("value can not be blank!");
        }

        return new Param(true, name, value, null, null);
    }

    public static Param multiPartParm(String name, String filename, byte[] content) {
        if (content == null) {
            throw new IllegalArgumentException("content can not be null!");
        }

        if (filename == null) {
            return new Param(false, name, null, name, content);
        }
        return new Param(false, name, null, filename, content);
    }

    public String URLEncode() {
        if (isHeader || this.value == null) {
            return "";
        }

        try {
            return URLEncoder.encode(this.name, "UTF-8") + "=" + URLEncoder.encode(this.value, "UTF-8");
        } catch (UnsupportedEncodingException ignored) {
            return null;
        }
    }

    @Override
    public String toString() {
        return "Param{" +
                "isHeader=" + isHeader +
                ", name='" + name + '\'' +
                ", value='" + value + '\'' +
                ", filename='" + filename + '\'' +
                '}';
    }
}
